import request from '../request'
import axios from 'axios'
import type { ClassTreeVO } from '@/types/organization'
import type { PageResult, UserVO, R } from '@/types/api'
import type { ImportResultStudentExcelDTO } from '@/types/student'

// 创建专门的下载实例
const downloadInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 60000, // 下载文件可能需要更长的超时时间
  responseType: 'blob'
})

// 添加请求拦截器
downloadInstance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 学生参数类型
interface StudentDTO {
  userCode: string      // 学号
  realName: string      // 姓名
  phone?: string        // 手机号
  email?: string        // 邮箱
  departmentId: number  // 班级ID
}

// 导入学生
const importStudents = (classId: number, file: File): Promise<ImportResultStudentExcelDTO> => {
  const formData = new FormData()
  formData.append('file', file, file.name)
  
  return request<ImportResultStudentExcelDTO>({
    url: `/v1/teacher/classes/${classId}/students/import`,
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
      'Accept': 'application/json'
    }
  })
}

// 导出学生
const exportStudents = async (classId: number) => {
  try {
    const response = await downloadInstance.get(
      `/v1/teacher/classes/${classId}/students/export`,
      {
        headers: {
          'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        }
      }
    )
    return response.data
  } catch (error: any) {
    if (error.response?.data instanceof Blob) {
      const text = await error.response.data.text()
      try {
        const errorData = JSON.parse(text)
        throw new Error(errorData.message || '导出失败')
      } catch {
        throw new Error('导出失败')
      }
    }
    throw error
  }
}

// 下载学生导入模板
const downloadStudentTemplate = async () => {
  try {
    const response = await downloadInstance.get(
      '/v1/teacher/classes/students/template',
      {
        headers: {
          'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        }
      }
    )
    return response.data
  } catch (error: any) {
    if (error.response?.data instanceof Blob) {
      const text = await error.response.data.text()
      try {
        const errorData = JSON.parse(text)
        throw new Error(errorData.message || '下载失败')
      } catch {
        throw new Error('下载失败')
      }
    }
    throw error
  }
}

// 导出未提交学生名单
const exportUnsubmittedStudents = async (taskId: number) => {
  try {
    const response = await downloadInstance.get(
      `/v1/tasks/${taskId}/submissions/unsubmitted/export`,
      {
        headers: {
          'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        }
      }
    )
    return response.data
  } catch (error: any) {
    if (error.response?.data instanceof Blob) {
      const text = await error.response.data.text()
      try {
        const errorData = JSON.parse(text)
        throw new Error(errorData.message || '导出失败')
      } catch {
        throw new Error('导出失败')
      }
    }
    throw error
  }
}

// 导出已提交文件列表
const exportSubmittedFiles = async (taskId: number) => {
  try {
    const response = await downloadInstance.get(
      `/v1/tasks/${taskId}/submissions/files/export`,
      {
        headers: {
          'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        }
      }
    )
    return response.data
  } catch (error: any) {
    if (error.response?.data instanceof Blob) {
      const text = await error.response.data.text()
      try {
        const errorData = JSON.parse(text)
        throw new Error(errorData.message || '导出失败')
      } catch {
        throw new Error('导出失败')
      }
    }
    throw error
  }
}

export const teacherClassApi = {
  // 获取教师负责的班级树
  getClassTree: () => {
    return request<ClassTreeVO[]>({
      url: '/v1/teacher/classes/tree',
      method: 'get'
    })
  },

  // 获取班级学生列表
  getClassStudents: (classId: number, params?: {
    userCode?: string
    realName?: string
    page?: number
    size?: number
  }) => {
    return request<PageResult<UserVO>>({
      url: `/v1/teacher/classes/${classId}/students`,
      method: 'get',
      params: {
        ...params,
        page: params?.page ?? 0,
        size: params?.size ?? 20
      }
    })
  },

  // 创建班级学生
  createStudent: (classId: number, data: StudentDTO) => {
    return request({
      url: `/v1/teacher/classes/${classId}/students`,
      method: 'post',
      data
    })
  },

  // 更新班级学生
  updateStudent: (classId: number, studentId: number, data: StudentDTO) => {
    return request({
      url: `/v1/teacher/classes/${classId}/students/${studentId}`,
      method: 'put',
      data
    })
  },

  // 删除班级学生
  deleteStudent: (classId: number, studentId: number) => {
    return request({
      url: `/v1/teacher/classes/${classId}/students/${studentId}`,
      method: 'delete'
    })
  },

  // 更新学生状态
  updateStudentStatus: (classId: number, studentId: number, status: boolean) => {
    return request({
      url: `/v1/teacher/classes/${classId}/students/${studentId}/status`,
      method: 'put',
      params: { status }
    })
  },

  // 重置学生密码
  resetStudentPassword: (classId: number, studentId: number) => {
    return request({
      url: `/v1/teacher/classes/${classId}/students/${studentId}/password/reset`,
      method: 'put'
    })
  },

  importStudents,
  exportStudents,
  downloadStudentTemplate,
  exportUnsubmittedStudents,
  exportSubmittedFiles
} 